package com.txd.mofa.shouye.aty;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.txd.mofa.R;
import com.txd.mofa.base.BaseAty;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.utils.SearchRecordTools;
import com.txd.mofa.view.ShanchuDialog;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Layout(R.layout.aty_seach)
public class SeachAty extends BaseAty {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    EditText tvSeach;
    @BindView(R.id.ll)
    LinearLayout ll;
    TagFlowLayout flow;
    TagFlowLayout flowHis;
    @BindView(R.id.tv_shanchu)
    TextView tvShanchu;
    private ImageView iv_sou;
    private LinearLayout ll_net;

    private List<String> listTitle = new ArrayList<>();
    private List<String> searchHistory;

    @Override
    public void initViews() {
        super.initViews();
        iv_sou = findViewById(R.id.iv_sou);
        ll_net = findViewById(R.id.ll_net);
        tvSeach = findViewById(R.id.tv_seach);
        flowHis = findViewById(R.id.flow_his);
        flow = findViewById(R.id.flow);

    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        ll_net.setVisibility(View.GONE);
    }

    @Override
    protected void onNetworkDisConnected() {

        if (flag == false) {
            ll_net.setVisibility(View.VISIBLE);
        }


    }


    @Override
    protected void onResume() {
        super.onResume();

        Huoqu();

        tuijianLishi();

        searchHistory = SearchRecordTools.getSearchHistory(me);

        flowHis.setAdapter(new TagAdapter(searchHistory) {
            @Override
            public View getView(FlowLayout parent, int position, Object o) {
                TextView tv = (TextView) LayoutInflater.from(me).inflate(R.layout.item_flow_seach,
                        flowHis, false);
                tv.setText((CharSequence) o);
                return tv;
            }
        });

    }

    private List<String> list = new ArrayList<>();

    private void tuijianLishi() {

        if (flag == false) {
            ll_net.setVisibility(View.VISIBLE);
        }

        HttpRequest.POST(me, search, new Parameter().add("token", token).add("name", ""), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")) {
                        ArrayList<Map<String, String>> data = JSONUtils.parseKeyAndValueToMapList(map.get("data"));


                        list.clear();
                        for (int i = 0; i < data.size(); i++) {
                            list.add(data.get(i).get("word"));
                        }

                        flow.setAdapter(new TagAdapter(list) {
                            @Override
                            public View getView(FlowLayout parent, int position, Object o) {
                                TextView tv = (TextView) LayoutInflater.from(me).inflate(R.layout.item_flow_seach,
                                        flow, false);
                                tv.setText((CharSequence) o);
                                return tv;
                            }
                        });


                    }

                } else {
                    toast("网络异常");
                }
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }


    @Override
    public void initDatas(JumpParameter paramer) {

    }

    @Override
    public void setEvents() {
        flow.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                SearchRecordTools.saveSearchHistory(me, list.get(position));
                jump(SeachResultAty.class, new JumpParameter().put("name", list.get(position)));
                return true;
            }
        });
        flowHis.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                SearchRecordTools.saveSearchHistory(me, searchHistory.get(position));
                jump(SeachResultAty.class, new JumpParameter().put("name", searchHistory.get(position)));
                return true;
            }
        });

        tvSeach.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                tvSeach.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            if (!tvSeach.getText().toString().trim().equals("") && tvSeach.getText().toString().trim() != null){
                                SearchRecordTools.saveSearchHistory(me, tvSeach.getText().toString());
                                jump(SeachResultAty.class, new JumpParameter().put("name", tvSeach.getText().toString()));
                                tvSeach.setText("");
                            }else {
                                Toast.makeText(me, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                            }
                           
                            return true;
                        }
                        return false;
                    }
                });
            }
        });

        tvSeach.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!tvSeach.getText().toString().trim().equals("") && tvSeach.getText().toString().trim() != null){
                        SearchRecordTools.saveSearchHistory(me, tvSeach.getText().toString());
                        jump(SeachResultAty.class, new JumpParameter().put("name", tvSeach.getText().toString()));
                        tvSeach.setText("");
                    }else {
                        Toast.makeText(me, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                    }

                    return true;
                }
                return false;
            }
        });

        iv_sou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tvSeach.getText().toString().trim().equals("") && tvSeach.getText().toString().trim() != null){
                    SearchRecordTools.saveSearchHistory(me, tvSeach.getText().toString());
                    jump(SeachResultAty.class, new JumpParameter().put("name", tvSeach.getText().toString()));
                    tvSeach.setText("");
                }else {
                    Toast.makeText(me, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.iv_back, R.id.tv_shanchu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_shanchu:
                ShanchuDialog shanchuDialog = new ShanchuDialog(me, "您确认要清除历史记录？", new ShanchuDialog.SignListener() {
                    @Override
                    public void shanchu() {
                        SearchRecordTools.getDelHistory(me);
                        onResume();
                        Toast.makeText(me, "删除成功", Toast.LENGTH_SHORT).show();
                    }
                });
                shanchuDialog.show();

                break;
        }
    }
}
